import ChatInput from '@/pages/VideoMeeting/chatInput';
import { Button, Divider, Space } from 'antd';
import { useEffect, useRef, useState } from 'react';
import styles from './chat.less';

const Chat = (props: {
  meetingArgument: string;
  chatMessageList?: [
    {
      userId: number | undefined;
      userName: string | undefined;
      chatMessage: string | undefined;
      createTime: string | undefined;
      avatar: string | undefined;
    },
  ];
  setChatMessageList: any;
}) => {
  const [meetingCode] = props.meetingArgument;
  const { chatMessageList, setChatMessageList } = props;
  const [chatReceivedMessage, setChatReceivedMessage] = useState<{
    messageType?: string;
    chatMessage?: string;
    userId?: string;
    userName?: string;
    createTime: string;
  }>();
  const userInfo = JSON.parse(localStorage.getItem('userInfo')!);
  const chatFrameRef = useRef<HTMLDivElement | null>(null);

  const sendMessage = async (message: {}) => {
    window.tm!.ipcRenderer.send(
      'send-websocket-message',
      JSON.stringify(message),
    );
  };
  useEffect(() => {
    if (chatReceivedMessage != null) {
      let avatar = '/img/user.png';
      if (userInfo.avatar != '' && userInfo.avatar != null) {
        avatar = userInfo.avatar;
      }
      const newMessage = {
        userId: parseInt(chatReceivedMessage.userId!),
        userName: chatReceivedMessage.userName,
        chatMessage: chatReceivedMessage.chatMessage,
        createTime: chatReceivedMessage.createTime,
        avatar: avatar,
      };
      if (chatMessageList != undefined) {
        const containFlag = chatMessageList.some((messageTmp) => {
          return (
            newMessage.chatMessage === messageTmp.chatMessage &&
            newMessage.createTime === messageTmp.createTime
          );
        });
        if (!containFlag) {
          const newChatMessage = chatMessageList?.concat(newMessage);
          setChatMessageList(newChatMessage);
        }
      } else {
        const newChatMessage = [];
        newChatMessage.push(newMessage);
        setChatMessageList(newChatMessage);
      }
    }
    chatFrameRef.current = null;
  }, [chatReceivedMessage]);
  useEffect(() => {
    // 在组件加载后，将滚动位置设置为底部
    if (chatFrameRef.current) {
      chatFrameRef.current!.scrollIntoView(true);
    }
  }, [chatFrameRef.current]);
  useEffect(() => {
    window.osn.on('chatMessage', (event: any, result: any) => {
      setChatReceivedMessage(result);
    });
  }, []);

  return (
    <div className={styles.chat}>
      <div className={styles.padding}>
        <div className={styles.chatTop}>
          <div className={styles.chatFrame}>
            {chatMessageList?.map((chatMessage, index) => {
              if (chatMessage.userId === userInfo.id) {
                return (
                  <div
                    className={styles.chatFrameContent}
                    ref={
                      index == chatMessageList?.length - 1
                        ? chatFrameRef
                        : undefined
                    }
                    key={index}
                  >
                    <div className={styles.chatFrameBubble}>
                      <span className={styles.span}>
                        {chatMessage.userName}
                      </span>
                      <button className={styles.button}>
                        {chatMessage.chatMessage}
                      </button>
                    </div>
                    <div className={styles.chatFrameAvatar}>
                      <img
                        className={styles.imgStyle}
                        src={chatMessage.avatar}
                      />
                    </div>
                  </div>
                );
              } else {
                return (
                  <div
                    className={styles.chatFrameContentLeft}
                    ref={
                      index == chatMessageList?.length - 1
                        ? chatFrameRef
                        : undefined
                    }
                    key={index}
                  >
                    <div className={styles.chatFrameAvatarLeft}>
                      <img
                        className={styles.imgStyle}
                        src={chatMessage.avatar}
                      />
                    </div>
                    <div className={styles.chatFrameBubbleLeft}>
                      <span className={styles.spanLeft}>
                        {chatMessage.userName}
                      </span>
                      <button className={styles.buttonLeft}>
                        {chatMessage.chatMessage}
                      </button>
                    </div>
                  </div>
                );
              }
            })}
          </div>
          <div>
            <Space>
              <Button
                size={'small'}
                onClick={() => {
                  //告知服务器发送聊天信息
                  const message = {
                    messageType: 'chatInput',
                    userId: userInfo.id,
                    userName: userInfo.userName,
                    chatMessage: '能听到我说话吗？',
                    meetingCode: meetingCode,
                  };
                  sendMessage(message);
                }}
              >
                能听到我说话吗？
              </Button>
              <Button
                size={'small'}
                onClick={() => {
                  //告知服务器发送聊天信息
                  const message = {
                    messageType: 'chatInput',
                    userId: userInfo.id,
                    userName: userInfo.userName,
                    chatMessage: '听得到',
                    meetingCode: meetingCode,
                  };
                  sendMessage(message);
                }}
              >
                听得到
              </Button>
              <Button
                size={'small'}
                onClick={() => {
                  //告知服务器发送聊天信息
                  const message = {
                    messageType: 'chatInput',
                    userId: userInfo.id,
                    userName: userInfo.userName,
                    chatMessage: '听不到',
                    meetingCode: meetingCode,
                  };
                  sendMessage(message);
                }}
              >
                听不到
              </Button>
            </Space>
          </div>
        </div>
        <Divider className={styles.divider} />
        <ChatInput meetingCode={meetingCode} />
      </div>
    </div>
  );
};

export default Chat;
